package main

import (
	"fmt"
	"os"
	"bufio"
	"Go-Exercise/immoc/functional/fib"
)

/**
 * @description 
 * @time 2018/5/6 16:43
 * @version
	1.确保调用再函数结束时发生
	2.defer 里面是一个栈，所以是先进后出的
	3.参数在defer语句时计算

	何时使用defer调用
	1.Open/Close
	2.Lock/Unlock
	3.printHeader/printFooter
 */
func main() {
	writeFile("fib.txt")
}

func tryDefer() {
	defer fmt.Println(1)
	defer fmt.Println(2)
	fmt.Println(3)
	fmt.Println(4)
}

func writeFile(filename string) {
	file, err := os.OpenFile(filename, os.O_EXCL|os.O_CREATE, 0666)
	if err != nil {
		if pathError, ok := err.(*os.PathError); !ok {
			panic(err)
		} else {
			fmt.Println(pathError.Op,
				pathError.Path,
				pathError.Err)
		}
		return
	}

	defer file.Close()

	writer := bufio.NewWriter(file)
	defer writer.Flush()
	f := fib.Fibonacci()
	for i := 0; i < 20; i++ {
		fmt.Fprintln(writer, f())
	}

}
